<template>
  <div class="scroll-top" @click="scrollTopSmooth" v-show="showTop">
    <svg-icon iconClass="back-to-top" className="icon-top" />
  </div>
</template>

<script>
import animation from '@/assets/js/animation'
import { throttle } from '@/assets/js/throttle'
export default {
  name: 'back-to-top',
  data () {
    return {
      scrollTop: 0
    }
  },
  computed: {
    showTop () {
      return this.scrollTop > 1000
    }
  },
  mounted () {
    window.addEventListener('scroll', throttle(this.getScrollTop, 300), true)
    // 用$on监听移除事件，不用在两个生命周期函数里定义
    this.$on('hook: beforeDestroy', () => {
      window.removeEventListener('scroll', this.getScrollTop, true)
    })
  },
  methods: {
    scrollTopSmooth () {
      // 获取页面的当前位置的高度
      this.getScrollTop()
      animation(this.scrollTop, 0, 8, val => {
        window.scrollTo(0, val)
      })
    },
    getScrollTop () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    }
  }
  // destroyed () {
  //   window.removeEventListener('scroll', this.getScrollTop, true)
  // }
}
</script>
<style lang='scss' scoped>
.scroll-top {
  position: fixed;
  right: px2rem(8);
  bottom: px2rem(85);
  .icon-top {
    width: px2rem(40);
    height: px2rem(40);
  }
}
</style>
